/**
 * Created by Zhaoyu on 2018/5/29.
 */
// eslint-disable-next-line no-undef

//参数
const params = getUrlVars();
console.log("params",params);
const id = params.id;
const type = params.type;

function getUrlVars() {
    let vars = [], hash;
    let hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (let i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = decodeURI(hash[1]);//解析中文
    }
    if(window.location.host.startsWith("http")){
        vars["server"] = window.location.host;
    }else{
        vars["server"] ="http://"+ window.location.host;
    }
    console.log(vars["server"]);
    console.log(vars);
    return vars;
}
console.log("id",id);


// eslint-disable-next-line no-undef
$(function(){
    // getUploadToken().then(token=>{
        let $count = 0,
            $photosCount = $("#photosCount"),
            $uploaderInput = $("#uploaderInput"),
            $uploaderImg = $("#uploaderImg"),
            $showBox = $("#showBox"),
            $btnUpload = $("#btnUpload"),
            $uploadLoading = $("#uploadLoading"),
            $btnText = $("#btnText")
        ;
        $uploadLoading.hide();

        let __file;
        $uploaderInput.on("change", function(e){
            __file = e.target.files[0];
            const reader = new FileReader();
            if(__file){
                reader.readAsDataURL(__file);
                reader.onload = function(event){
                    if(__file.type.startsWith("image")){
                        $uploaderImg[0].style.display = "block";
                        $uploaderImg.attr({src:event.target.result});
                        $showBox.hide()
                    }
                };
            }
        });

        let imgFormData = new FormData();
        $uploaderImg.on("load", ()=>imgLoad());
        function imgLoad(){
            // 重新初始化FormData并添加文件
            imgFormData = new FormData();
            const img = $uploaderImg[0];
            const imgWidth=img.naturalWidth || img.width;
            //手机显示
            if(imgWidth>document.body.clientWidth){
                $uploaderImg.attr({width:"100%"})
            }else{
                $uploaderImg.removeAttr("width")
            }
            // 直接使用原始文件，不添加水印
            if(__file){
                imgFormData.append("file", __file);
                console.log("文件已添加到FormData:", __file.name, __file.size);
            }
            return imgFormData;
        }

        $btnUpload.on('click', ()=>{
            if($uploaderImg[0].style.display==="none"){
                alert("请先选择照片");
            } else if($uploaderImg[0].style.display==="block"){
                // 确保有文件才进行上传
                if(!__file){
                    alert("请先选择照片文件");
                    return;
                }
                // 重新创建FormData确保包含文件
                const uploadFormData = new FormData();
                uploadFormData.append("file", __file);
                console.log("准备上传文件:", __file.name, __file.size);
                uploadFile(uploadFormData);
            }
        });

        function uploadFile(formData) {
            //loading
            $btnUpload.addClass("weui-btn_loading");
            $btnText.text("上传中");
            $uploadLoading.show();
            
            // 调试：检查FormData内容
            console.log("formData", formData);
            for (let pair of formData.entries()) {
                console.log('FormData内容:', pair[0], pair[1]);
            }
            
            // 添加必要的参数
            formData.append("id", id);
            formData.append("type", "file");
            formData.append("timestamp", Date.now());
            
            // 再次检查FormData内容
            console.log("添加参数后的FormData:");
            for (let pair of formData.entries()) {
                console.log('FormData内容:', pair[0], pair[1]);
            }
            
            // 使用fetch API替代axios
            return fetch(type==="return"?"/assets/uploadReturnImage":"/assets/uploadFaultImage", {
                method: 'POST',
                body: formData
            })
                .then((response) => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then((data) => {
                    $count++;
                    $photosCount.text($count);

                    $btnUpload.removeClass("weui-btn_loading");
                    $btnText.text("上传");
                    $uploadLoading.hide();
                    alert("上传成功");
                })
                .catch((error) => {
                    console.log("error:", error);
                    $btnUpload.removeClass("weui-btn_loading");
                    $btnText.text("上传");
                    $uploadLoading.hide();
                    alert("上传失败，错误：" + error.message);
                });
        }
    // });
});